package top.yehot.kettle.boot.service.abstracts;

import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import top.yehot.cmm.util.core.base.BaseException;
import top.yehot.kettle.boot.core.utils.FileUtil;
import top.yehot.kettle.boot.enums.KettleResEnum;
import top.yehot.kettle.boot.enums.RepTypeEnum;
import top.yehot.kettle.boot.mapper.RepositoryMapper;
import top.yehot.kettle.boot.models.entity.Repository;
import top.yehot.kettle.boot.models.vo.repository.RepoAddVO;

/**
 * 资源库 服务抽象类
 * 
 * @author lquan
 * @date 2022年5月29日 下午5:16:07
 */
public abstract class AbstractRepositoryService extends ServiceImpl<RepositoryMapper, Repository> {

	/**
	 * 封装参数
	 */
	protected Repository packageRepository(Object param) {
		// 参数合法校验
		requiredVali((RepoAddVO) param);
		// 拷贝对象
		Repository newRepo = new Repository();
		BeanUtils.copyProperties(param, newRepo);
		// 根据资源库类型重置属性
		modifyRepo(newRepo);
		return newRepo;
	} 
	
	/**
	 * 根据资源库类型重置属性
	 */
	protected void modifyRepo(Repository repo) {
		if (RepTypeEnum.file == repo.getRepType()) {
			String repBasePath = FileUtil.removeEndSlash(repo.getRepBasePath());
			repo.setRepBasePath(repBasePath);
			repo.setDbType(null);
			repo.setDbAccess(null);
			repo.setDbHost(null);
			repo.setDbPort(null);
			repo.setDbName(null);
			repo.setDbUsername(null);
			repo.setDbPassword(null);
		} else {
			repo.setRepBasePath(null);
		}
	}
	
	/**
	 * 必填项验证
	 */
	protected void requiredVali(RepoAddVO param) {
		if (RepTypeEnum.file == param.getRepType() && !StringUtils.hasText(param.getRepBasePath())) {
			throw new BaseException(KettleResEnum.repBasePath_vali);
		}
		if (RepTypeEnum.db == param.getRepType()) {
			if (!StringUtils.hasText(param.getDbType())) {
				throw new BaseException(KettleResEnum.dbType_vali);
			}
			if (!StringUtils.hasText(param.getDbAccess())) {
				throw new BaseException(KettleResEnum.dbAccess_vali);
			}
			if (!StringUtils.hasText(param.getDbHost())) {
				throw new BaseException(KettleResEnum.dbHost_vali);
			}
			if (!StringUtils.hasText(param.getDbPort())) {
				throw new BaseException(KettleResEnum.dbPort_vali);
			}
			if (!StringUtils.hasText(param.getDbName())) {
				throw new BaseException(KettleResEnum.dbName_vali);
			}
			if (!StringUtils.hasText(param.getDbUsername())) {
				throw new BaseException(KettleResEnum.dbUsername_vali);
			}
			if (!StringUtils.hasText(param.getDbPassword())) {
				throw new BaseException(KettleResEnum.dbPassword_vali);
			}
		}
	}
	
}
